package com.travelsky.login.infrastructure;

import com.travelsky.login.domain.Account;
import com.travelsky.login.domain.AccountRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

@Repository
class AccountRepositoryAdapter implements AccountRepository {

  private final JdbcTemplate jdbcTemplate;

  @Autowired
  public AccountRepositoryAdapter(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  /**
   * 通过用户名查找账户信息
   *
   * @param userId 用户名
   * @return 账户信息
   */
  @Override
  public Account findBy(String userId) {
    String sql = "SELECT * FROM USER WHERE USERID = ?";
    List<Account> accounts = jdbcTemplate.query(sql, new Object[]{userId},
        (rs, i) -> new Account()
            .setUserId(rs.getString("USERID"))
            .setLastLoginTime(rs.getString("LASTLOGINTIME"))
            .setLocked("1".equals(rs.getString("LOCKED")))
            .setPassword(rs.getString("PASSWORD")));
    if (CollectionUtils.isEmpty(accounts)) {
      return null;
    }
    return accounts.get(0);
  }

}
